package com.heima.lock.sjms.单例模式.双检锁03;

import java.io.*;

/**
 * @author 陈辉
 * @data 2024 11:07
 * <p>
 * 设计模式：编程套路，从编程发展至今，一共总结出32套优秀的编程套路。
 * <p>
 * 单例：一个类在全局只产生一个对象
 * 懒汉式：不用不创建，用的时候才创建   -- 懒加载
 */

public class Student implements Serializable { }

class Demo {

    public static Student stu;

    public static void main(String[] args) throws Exception {
        Student stu1 = getStu();
        System.out.println("stu1 = " + stu1);

        Class clazz = stu1.getClass();
        Student stu2 = (Student) clazz.newInstance();
        System.out.println("stu2 = " + stu2);

        //对stu1进行序列化操作
        ObjectOutputStream oos  = new ObjectOutputStream(new FileOutputStream("D:\\a.txt"));
        oos.writeObject(stu1);
        oos.close();

        //对stu1进行反序列化操作
        ObjectInputStream ois  = new ObjectInputStream(new FileInputStream("D:\\a.txt"));
        Student stu3 = (Student) ois.readObject();
        System.out.println("stu3 = " + stu3);
        ois.close();

    }

    public static Student getStu() {
        synchronized ("abc") {
            if (stu == null) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                stu = new Student();
            }
        }

        return stu;
    }
}
